﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.Linq;
using System.Web;
using TimeProject.Engine.DbModels;
using TimeProject.Engine.Providers;

namespace TimeProject.WebSite.Exports
{
    [Export(typeof(IEntityPublicIdProvider))]
    [TimeProjectPriority]
    public class EntityPublicIdProvider : IEntityPublicIdProvider
    {
        public string GetPublicId(User entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            string s = MakePublicId("U", entity.Id, entity.Username);
            return s;
        }

        public string GetPublicId(Organization entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            string s = MakePublicId("O", entity.Id, entity.Code);
            return s;
        }

        public bool TryParseEntityId(string publicId, out int result)
        {
            result = 0;

            if (publicId == null)
            {
                throw new ArgumentNullException("publicId");
            }

            int index = publicId.IndexOf('-');
            if (index <= 1)
            {
                return false;
            }

            string id = publicId.Substring(1, index - 1);

            return int.TryParse(id, out result);
        }

        private static string MakePublicId(string typeLetter, int id, string text)
        {
            string s = string.Format("{0}{1}-{2}", typeLetter, id.ToString(CultureInfo.InvariantCulture), text.ToUpper());
            return s;
        }

    }
}